<?php

declare(strict_types=1);

namespace App\Controller\Api;

use Hyperf\HttpServer\Contract\RequestInterface;
use Service\AppService\IdService;
use App\Service\Code\Normal;
use App\Service\AppService\RedisRedLock;
use App\Model\PssModel\Stock;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Controller\AbstractController;
use App\Service\CommodityService\BbcBestGoodsService;
use App\Model\PssModel\Business;
use App\Service\OrderService\OrderMessageService;
use App\Service\TaskServer\TaskWorker;
use App\Service\UserService\FQLService;
use Service\CommodityService\StockRedisService;
use Service\CommodityService\StockMysqlService;

/**
 * @Controller(prefix="/test")
 * @author Administrator
 */
class TestController extends AbstractController
{ 
    
    /**
     * @RequestMapping(path="loadGwOrderTest/{CustomerCode}/{commoditySKU}", methods="post,get")
     * @return string[]
     */
    public function loadGwOrderTest($CustomerCode,$commoditySKU)
    {
        $json = '{"placeOrderInfo":{"SingleChannel":"云仓商城","customerCode":"sxdt1001","CompanyOrderCode":"640598913761075202","ShopOrderCode":"20221103171122227665","receiverName":"张润琪","receiverPhone":"18328093040","province":"四川省","city":"成都市","district":"成华区","ReceiverAddress":"中国四川省成都市成华区双华路","paymentName":"张润琪","paymentPhone":"18328093040","paymentCart":"510183200007063913","payment":99,"isDeclarePay":true,"isOrderDeclare":false,"totalPrice":9.6,"freight":0,"taxPrice":0,"DiscountPrice":0,"palceOrderCommoditys":[{"batchID":"508291789824720907","commodityCount":"2","commoditySKU":"DC4543268095617","commodityRealPrice":4.8,"commodityName":"三和本铺美白肌丽面霜30g","index":1}],"payerFlowNo":"","PayCommanyName":"","PayCommanyCode":"","deliveryUrl":null,"cancelUrl":null,"orderType":0},"extendedParameters":{"jdOrderType":"0","orderType":"","shop":"","remark":""}}';
        $data = json_decode($json,true);
        
        $company_code = IdService::instance()->getOtherID();
        $company_code = 'LoadOrderTest_'.$company_code;
        $data['placeOrderInfo']['customerCode'] = $CustomerCode;
        $data['placeOrderInfo']['CompanyOrderCode'] = $data['placeOrderInfo']['ShopOrderCode'] = $company_code;
        $data['placeOrderInfo']['palceOrderCommoditys'][0]['commoditySKU'] = $commoditySKU;
        
        $url = 'http://125.71.226.153:1098/customserver/placeorder';
        $form_data = [
            'tag'           => 'shopcustom_createOrder',
            'uid'           => $company_code,
            'company_code'  => $company_code,
            'url'           => $url,
            'data'          => $data,
            'method'        => 'post',
            'format'        => 'json',
            'header'        => [],
        ];
        $resTask = TaskWorker::instance()->addTask([$form_data]);
        $resTask = current($resTask);
        $result  = @json_decode((string)$resTask['response']['result'],true);
        if( $resTask['response']['httpCode'] != Normal::SUC ) {
            $msg = !empty($result) ? ($result['message']??'请求失败') : $resTask['response']['result'] ;
            $msg = $msg ? $msg : '接口请求失败';
            return Normal::returnCode(Normal::FAIL,$msg);
        }
        
        $url = 'http://125.71.226.153:1098/customserver/placeorderconfirm';
        $json = '{"placeOrderConfirmInfo":{"CompanyOrderCode":"640598913761075202","isConfirm":true,"payerFlowNo":"102221103171105060001","payCommanyName":"新生支付有限公司","payCommanyCode":"460116287K","EnterpriseCode":"5101360A9E","EBPName":"成都麦帮信息科技有限公司","EBCCode":"","LogisticsCode":"","PortNo":"","DeclareOrderSn":"640598913761075202","SkipOrderDelcare":false,"SkipWayBillDeclare":false,"SkipInventoryDeclare":false}}';
        $data = json_decode($json,true);
        $data['placeOrderConfirmInfo']['CompanyOrderCode'] = $company_code;
        $form_data = [
            'tag'           => 'shopcustom_pay',
            'uid'           => $company_code,
            'company_code'  => $company_code,
            'url'           => $url,
            'data'          => $data,
            'method'        => 'post',
            'format'        => 'json',
            'header'        => [],
        ];
        $resTask = TaskWorker::instance()->addTask([$form_data]);
        $resTask = current($resTask);
        $result  = @json_decode((string)$resTask['response']['result'],true);
        if( $resTask['response']['httpCode'] != Normal::SUC ) {
            $msg = !empty($result) ? ($result['message']??'请求失败') : $resTask['response']['result'] ;
            return Normal::returnCode(Normal::FAIL,$msg);
        }
        
        return Normal::returnCode(Normal::SUC,"支付成功",[
            'orderSn'   => $company_code
        ]);
    }
    
    /**
     * @RequestMapping(path="sendMsg", methods="post,get")
     * @return string[]
     */
    public function sendMsg(RequestInterface $request)
    {
        $body  = $request->getParsedBody();
        $binfo = Business::instance()->getUserInfoByBid($body['bid']);
        $parameters = array_merge($binfo,$body);
        try {
            $client = new \Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
            $client->connect('0.0.0.0', 9504);
            $json = '{"requestMethod":"CommodityService.BbcBestGoodsService.getBestGoodsPageList","requestData":{"bid":163,"user_tag":"","yx_template_id":"304555216693364610","hz_template_id":"304255408724248450"}}';
            $client->send($json."\n");
            $rst = null;
            while ( $result = $client->recv() ) {
                echo $result.PHP_EOL;
                $rst .= $result;
            }
            
            echo $rst.PHP_EOL;DIE;
            $return = @json_decode($rst,true);
            $client->close();
            return $result;
        } catch ( \Throwable $e ) {
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }
    }
    
    /**
     * @RequestMapping(path="orderDispatchGoods", methods="post,get")
     * @return string[]
     */
    public function orderDispatchGoods(RequestInterface $request)
    {
        $body  = $request->getParsedBody();
        $binfo = Business::instance()->getUserInfoByBid($body['bid']);
        $parameters = array_merge($binfo,$body);
        return BbcBestGoodsService::instance()->getDispatchGoodsList($parameters);
    }
    
    /**
     * @RequestMapping(path="bestGoodsPageList", methods="post,get")
     * @return string[]
     */
    public function bestGoodsPageList(RequestInterface $request)
    {
        $body  = $request->getParsedBody();
        $binfo = Business::instance()->getUserInfoByBid($body['bid']);
        $parameters = array_merge($binfo,$body);
        return BbcBestGoodsService::instance()->getBestGoodsPageList($parameters);
    }
    
    /**
     * @RequestMapping(path="deduct", methods="post,get")
     * @return string[]
     */
    public function deduct(RequestInterface $request) 
    {
        $stockKeys = $request->getParsedBody();
        $uuid = (string) (IdService::instance()->getOtherID());
        try {
            
            //获取锁
            $isLock = RedisRedLock::instance()->getMultiLock($stockKeys,$uuid);
            if( !$isLock ) {
                return Normal::returnCode(Normal::FAIL,"当前商品抢购繁忙，请稍后再试");
            }
            
            Stock::instance()->startTrans();
            
            //开始扣减库存
            $res = Stock::instance()->deductGoodsStock($stockKeys);
            if( $res['code'] != Normal::SUC ) {
                Stock::instance()->rollback();
                return $res;
            }
            
            //解锁，解锁失败则回滚，成功则提交事务
            $isUnLock = RedisRedLock::instance()->getMultiUnLock($stockKeys, $uuid);
            if( !$isUnLock ) {
                Stock::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"当前商品抢购繁忙，请稍后再试");
            }
            
            Stock::instance()->commit();
            return Normal::returnCode(Normal::SUC,"操作成功");
        } catch ( \Throwable $e ) {
            RedisRedLock::instance()->getMultiUnLock($stockKeys, $uuid);
            Stock::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }
    }
    
    /**
     * @RequestMapping(path="uploadFenQiLeImage", methods="post")
     * @return string[]
     */
    public function uploadFenQiLeImage(RequestInterface $request,FQLService $service)
    {
        $body = $request->getParsedBody();
        return $service->uploadSingleProductImageByProductID($body['product_id'],$body['sku_id'],$body['images']);
    }
    
    /**
     * @RequestMapping(path="getid", methods="get")
     */
    public function getid(RequestInterface $request)
    {
        $id = IdService::instance()->getOtherID();
        $logid = IdService::instance()->getLogID();
        $return =  [
            'id'    => $id,
            'pd' => $logid,
            'gd'    => IdService::instance()->getGoodsID()   
        ];
        print_r($return);
    }

    /**
     * @RequestMapping(path="testSendMsg", methods="post,get")
     * @return string[]
     */
    public function testSendMsg(RequestInterface $request)
    {
        //测试redis
        $redis = redis();

        $binfo = [
            'bid' => 163
        ];
        $key = 'SendOrderAccountArrearsMessage_' . 1;
        $expire = strtotime(date('Y-m-d 23:59:59')) - time();
        $redis->set($key,$key,$expire);
//        $body  = $request->getParsedBody();
        OrderMessageService::instance()->publish(2,'13689629337',[
            'bid' => 2
        ]);
        print_r("提交完成");
//        print_r($body);
    }
    
    /**
     * @RequestMapping(path="testGoods", methods="post,get")
     * @return string[]
     */
    public function testGoods()
    {
        $args = [
            'bid'               => 163,
            'goods_list'        => [
                [
                    'skucode'   => '2310111531385139',
                    'goods_id'  => '765597627503869952',
                    'batch_no'  => '基准批次',
                    'spec_num'  => 1,
                    'goods_num' => 1,
                ]
            ],
            'isBbcOrder'        => 1,
            'is_router_user'    => 0,
        ];
        $res = callRpcCommodityServer('getOrderRealGoodsList',$args);
        print_r($res);
        return $res;

    }
    
    /**
     * @RequestMapping(path="deductStock", methods="get")
     * @return string[]
     */
    public function deductStock(StockRedisService $service)
    {
        $return = $service->decrease('909012974339883008',1);
        if( $return['code'] == \Service\Code\Normal::SUC ) {
            echo json_encode($return,JSON_UNESCAPED_UNICODE).PHP_EOL;
        }
        return $return;
    }
}